<template>
  <div class="map-container">
    <h1>WFS Demo - 完整 CRUD 功能</h1>
    <div class="controls">
      <div class="basemap-control">
        <label>底图选择：</label>
        <select v-model="selectedBasemap" @change="changeBasemap">
          <option value="none">无底图</option>
          <option value="arcgis">ArcGIS世界街道图</option>
        </select>
        <button @click="saveFeatures">保存绘制</button>
        <button @click="updateSelectedFeature" :disabled="!selectedFeature">更新选中</button>
        <button @click="deleteSelectedFeature" :disabled="!selectedFeature">删除选中</button>
        <button @click="queryFeatures">查询要素</button>
      </div>
      <div class="draw-control">
        <label>几何类型：</label>
        <select v-model="selectedGeometryType" @change="handleGeometryTypeChange">
          <option value="Point">点</option>
          <option value="LineString">线</option>
          <option value="Polygon">面</option>
          <option value="None">无</option>
        </select>
        <input v-model="queryFilter" placeholder="属性过滤条件" style="margin-left: 10px; padding: 4px;">
      </div>
    </div>
    <div id="map" ref="mapContainer" class="map"></div>
    
    <!-- 要素详细信息悬浮弹窗 -->
    <div v-if="showFeatureInfo" 
         class="feature-info-popup"
         :style="{ 
           left: popupPosition.x + 'px', 
           top: popupPosition.y + 'px',
           transform: 'none'  /* 禁用默认居中 transform */ 
         }"
         @mousedown="startDrag">
      <div class="popup-header">
        <h3>要素详细信息</h3>
        <button @click="closeFeatureInfo" class="close-btn">&times;</button>
      </div>
      <div class="popup-content">
        <div v-if="selectedFeatureData">
          <div class="info-section">
            <h4>基本属性</h4>
            <div class="info-grid">
              <div class="info-item">
                <label>ID:</label>
                <span>{{ selectedFeatureData.id }}</span>
              </div>
              <div class="info-item">
                <label>几何类型:</label>
                <span>{{ selectedFeatureData.geometryType }}</span>
              </div>
              <div class="info-item">
                <label>图层:</label>
                <span>{{ selectedFeatureData.layer }}</span>
              </div>
            </div>
          </div>
          
          <div class="info-section">
            <h4>属性字段</h4>
            <div class="info-grid">
              <div v-for="(value, key) in selectedFeatureData.properties" :key="key" class="info-item">
                <label>{{ key }}:</label>
                <span>{{ value }}</span>
              </div>
            </div>
          </div>
          
          <div class="info-section">
            <h4>坐标信息</h4>
            <div class="coordinates">
              <p><strong>坐标范围:</strong></p>
              <p>最小X: {{ selectedFeatureData.bounds.minX.toFixed(6) }}</p>
              <p>最小Y: {{ selectedFeatureData.bounds.minY.toFixed(6) }}</p>
              <p>最大X: {{ selectedFeatureData.bounds.maxX.toFixed(6) }}</p>
              <p>最大Y: {{ selectedFeatureData.bounds.maxY.toFixed(6) }}</p>
            </div>
          </div>
        </div>
        <div v-else class="loading">
          <p>正在加载要素信息...</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, onUnmounted } from 'vue';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import { bbox } from 'ol/loadingstrategy.js';
import Style from 'ol/style/Style.js';
import Stroke from 'ol/style/Stroke.js';
import Fill from 'ol/style/Fill.js';
import Circle from 'ol/style/Circle.js';
import XYZ from 'ol/source/XYZ.js';
import { fromLonLat } from 'ol/proj.js';
import WFS from 'ol/format/WFS.js';
import Select from 'ol/interaction/Select.js';
import Modify from 'ol/interaction/Modify.js';
import Draw from 'ol/interaction/Draw.js';
import { defaults as defaultInteractions } from 'ol/interaction.js';
import { click } from 'ol/events/condition.js';
import {get, transform} from 'ol/proj.js';
import Feature from 'ol/Feature.js';
import MultiPolygon from 'ol/geom/MultiPolygon.js';
import Point from 'ol/geom/Point.js';
import MultiLineString from 'ol/geom/MultiLineString.js';

const mapContainer = ref(null);
const selectedBasemap = ref('none');
const selectedGeometryType = ref('None');
const queryFilter = ref('');
const selectedFeature = ref(null); // 当前选中的要素
const showFeatureInfo = ref(false); // 控制悬浮弹窗显示
const selectedFeatureData = ref(null); // 选中要素的数据
const isDragging = ref(false); // 是否正在拖动
const dragOffset = ref({ x: 0, y: 0 }); // 拖动偏移量
const popupPosition = ref({ x: 0, y: 0 }); // 弹窗位置

let map = null;
let basemapLayers = {};
let draw = null;
let vectorSource1 = null;
let vectorSource2 = null;
let vectorSource3 = null;
let select = null;
let modify = null;

// 保存新绘制的要素
const saveFeatures = function(){
  console.log('执行保存功能');
  const features = vectorSource1.getFeatures();
  if (features.length === 0) {
    alert('没有要保存的要素');
    return;
  }
  const lastFeature = features[features.length - 1];
  saveDrawnFeature(lastFeature, selectedGeometryType.value);
};

// 更新选中的要素
const updateSelectedFeature = function() {
  if (!selectedFeature.value) {
    alert('请先选择一个要素');
    return;
  }
  updateFeature(selectedFeature.value);
};

// 删除选中的要素
const deleteSelectedFeature = function() {
  if (!selectedFeature.value) {
    alert('请先选择一个要素');
    return;
  }
  
  if (confirm('确定要删除这个要素吗？')) {
    deleteFeature(selectedFeature.value);
  }
};

// 关闭要素信息弹窗
const closeFeatureInfo = function() {
  showFeatureInfo.value = false;
  selectedFeatureData.value = null;
  // 重置弹窗位置到屏幕中央
  setTimeout(() => {
    const centerX = (window.innerWidth - 500) / 2;
    const centerY = (window.innerHeight - 400) / 2;
    popupPosition.value = {
      x: Math.max(10, centerX),
      y: Math.max(10, centerY)
    };
  }, 100);
};

// 开始拖动
const startDrag = function(event) {
  if (event.target.classList.contains('close-btn')) {
    return; // 如果点击的是关闭按钮，不开始拖动
  }
  
  isDragging.value = true;
  const popup = event.currentTarget;
  const rect = popup.getBoundingClientRect();
  
  dragOffset.value = {
    x: event.clientX - rect.left,
    y: event.clientY - rect.top
  };
  
  // 添加全局事件监听器
  document.addEventListener('mousemove', drag);
  document.addEventListener('mouseup', stopDrag);
  
  event.preventDefault();
};

// 拖动过程中
const drag = function(event) {
  if (!isDragging.value) return;
  
  popupPosition.value = {
    x: event.clientX - dragOffset.value.x,
    y: event.clientY - dragOffset.value.y
  };
  
  event.preventDefault();
};

// 停止拖动
const stopDrag = function() {
  isDragging.value = false;
  
  // 移除全局事件监听器
  document.removeEventListener('mousemove', drag);
  document.removeEventListener('mouseup', stopDrag);
};

// 查询要素
const queryFeatures = function() {
  if (!selectedFeature.value) {
    // 如果没有选中的要素，则执行原有的过滤查询
    const filter = queryFilter.value.trim();
    loadFeaturesWithFilter(filter);
  } else {
    // 如果有选中的要素，则查询该要素的详细信息
    queryFeatureInfo(selectedFeature.value);
  }
};

// 查询选中要素的详细信息
const queryFeatureInfo = async function(feature) {
  try {
    showFeatureInfo.value = true;
    selectedFeatureData.value = null;
    
    // 设置弹窗初始位置为屏幕中央
    const centerX = (window.innerWidth - 500) / 2;
    const centerY = (window.innerHeight - 400) / 2;
    popupPosition.value = {
      x: Math.max(10, centerX),
      y: Math.max(10, centerY)
    };
    
    const geometry = feature.getGeometry();
    if (!geometry) {
      throw new Error('要素没有几何信息');
    }
    
    // 获取要素的基本信息
    const featureId = feature.getId() || '未知ID';
    const geometryType = geometry.getType();
    const targetLayer = getTargetLayerByGeometry(geometry);
    
    // 计算几何边界
    const extent = geometry.getExtent();
    const bounds = {
      minX: extent[0],
      minY: extent[1],
      maxX: extent[2],
      maxY: extent[3]
    };
    
    // 获取要素属性（如果有的话）
    const properties = {};
    const keys = feature.getKeys();
    keys.forEach(key => {
      if (key !== 'geometry' && key !== 'geom') {
        properties[key] = feature.get(key);
      }
    });
    
    // 构建要素数据对象
    selectedFeatureData.value = {
      id: featureId,
      geometryType: geometryType,
      layer: targetLayer,
      properties: Object.keys(properties).length > 0 ? properties : { '无属性数据': '该要素没有额外的属性信息' },
      bounds: bounds
    };
    
    console.log('要素信息:', selectedFeatureData.value);
    
  } catch (error) {
    console.error('查询要素信息时出错:', error);
    alert('查询要素信息失败: ' + error.message);
    showFeatureInfo.value = false;
  }
};

// 坐标转换功能函数
function transformCoordinates(coordinates, sourceProj, targetProj) {
  if (Array.isArray(coordinates) && coordinates.length >= 2 && typeof coordinates[0] === 'number') {
    // 直接使用OpenLayers的transform函数进行坐标转换
    const transformed = transform(coordinates, sourceProj, targetProj);
    console.log(`坐标转换: ${coordinates} -> ${transformed}`);
    return transformed; // 直接返回转换后的坐标，不要颠倒顺序
  } else if (Array.isArray(coordinates)) {
    // 对于嵌套数组，递归转换每个坐标
    return coordinates.map(coord => transformCoordinates(coord, sourceProj, targetProj));
  }
  return coordinates;
}

// 统一的几何类型到图层映射函数
function getTargetLayerByGeometry(geometry) {
  const geometryType = geometry.getType();
  if (geometryType === 'Point') {
    return 'city';
  } else if (geometryType === 'MultiLineString' || geometryType === 'LineString') {
    return 'bou2_4l';
  } else if (geometryType === 'MultiPolygon' || geometryType === 'Polygon') {
    return 'bou2_4p';
  }
  throw new Error(`不支持的几何类型: ${geometryType}`);
}

// 保存新要素到GeoServer
function saveDrawnFeature(feature, type) {
  try {
    const geometry = feature.getGeometry();
    if (!geometry) {
      throw new Error('无效的几何对象');
    }
    
    const newFeature = new Feature();
    newFeature.setGeometryName('geom');
    
    let processedGeometry = null;
    const originalCoordinates = geometry.getCoordinates();
    console.log('原始坐标:', JSON.stringify(originalCoordinates));
    
    const convertedCoordinates = transformCoordinates(originalCoordinates, 'EPSG:3857', 'EPSG:4326');
    console.log('转换到EPSG:4326后的坐标:', JSON.stringify(convertedCoordinates));

    // 修复：统一几何类型处理逻辑（支持原始类型和Multi类型）
    const geometryType = geometry.getType();
    console.log('原始几何类型:', geometryType);
    
    if (geometryType === 'Point') {
  const pointCoords = [convertedCoordinates[1], convertedCoordinates[0]];
  processedGeometry = new Point(pointCoords);
} else if (geometryType === 'LineString') {
  const swappedCoords = convertedCoordinates.map(coord => [coord[1], coord[0]]);
  processedGeometry = new MultiLineString([swappedCoords]);
} else if (geometryType === 'MultiLineString') {
       // 对于已有的MultiLineString，交换坐标顺序为[latitude, longitude]
       const swappedLines = convertedCoordinates.map(line => 
         line.map(coord => [coord[1], coord[0]])
       );
       processedGeometry = new MultiLineString(swappedLines);
     } else if (geometryType === 'Polygon') {
       const swappedRings = convertedCoordinates.map(ring => ring.map(coord => [coord[1], coord[0]]));
       processedGeometry = new MultiPolygon([swappedRings]);
     } else if (geometryType === 'MultiPolygon') {
       // 对于已有的MultiPolygon，交换坐标顺序为[latitude, longitude]
       const swappedPolygons = convertedCoordinates.map(polygon => 
         polygon.map(ring => ring.map(coord => [coord[1], coord[0]]))
       );
       processedGeometry = new MultiPolygon(swappedPolygons);
    } else {
      throw new Error(`不支持的几何类型: ${geometryType}`);
    }

    if (!processedGeometry) {
      throw new Error('几何对象创建失败');
    }

    newFeature.setGeometry(processedGeometry);
    
    // 使用统一的目标图层映射函数（传入原始几何对象）
    let targetLayer = getTargetLayerByGeometry(geometry);
    console.log('目标图层:', targetLayer);
    
    // WFS 插入事务
    const wfsTransaction = new WFS().writeTransaction(
      [newFeature],
      null,
      null,
      {
        featureNS: 'www.testmap.com',
        featurePrefix: 'testmap',
        featureType: targetLayer,
        srsName: 'EPSG:4326'
      }
    );
    
    sendWFSRequest(wfsTransaction, 'insert');
    
  } catch (error) {
    console.error('保存过程中发生错误:', error);
    alert('保存失败: ' + error.message);
  }
}

// 更新要素
function updateFeature(feature) {
  try {
    const geometry = feature.getGeometry();
    if (!geometry) {
      throw new Error('无效的几何对象');
    }

    const featureId = feature.getId();
    if (!featureId) {
      throw new Error('要素没有ID，无法更新');
    }

    const updatedFeature = new Feature();
    updatedFeature.setId(featureId);
    updatedFeature.setGeometryName('geom');
    
    let processedGeometry = null;
    const originalCoordinates = geometry.getCoordinates();
    const convertedCoordinates = transformCoordinates(originalCoordinates, 'EPSG:3857', 'EPSG:4326');

    // 修复：统一几何类型处理逻辑（支持原始类型和Multi类型）
    const geometryType = geometry.getType();
    console.log('原始几何类型:', geometryType);
    
    if (geometryType === 'Point') {
  const pointCoords = [convertedCoordinates[1], convertedCoordinates[0]];
  processedGeometry = new Point(pointCoords);
} else if (geometryType === 'LineString') {
  const swappedCoords = convertedCoordinates.map(coord => [coord[1], coord[0]]);
  processedGeometry = new MultiLineString([swappedCoords]);
} else if (geometryType === 'MultiLineString') {
       // 对于已有的MultiLineString，交换坐标顺序为[latitude, longitude]
       const swappedLines = convertedCoordinates.map(line => 
         line.map(coord => [coord[1], coord[0]])
       );
       processedGeometry = new MultiLineString(swappedLines);
     } else if (geometryType === 'Polygon') {
       const swappedRings = convertedCoordinates.map(ring => ring.map(coord => [coord[1], coord[0]]));
       processedGeometry = new MultiPolygon([swappedRings]);
     } else if (geometryType === 'MultiPolygon') {
       // 对于已有的MultiPolygon，交换坐标顺序为[latitude, longitude]
       const swappedPolygons = convertedCoordinates.map(polygon => 
         polygon.map(ring => ring.map(coord => [coord[1], coord[0]]))
       );
       processedGeometry = new MultiPolygon(swappedPolygons);
    } else {
      throw new Error(`不支持的几何类型: ${geometryType}`);
    }

    if (!processedGeometry) {
      throw new Error('几何对象创建失败');
    }

    updatedFeature.setGeometry(processedGeometry);
    
    // 修复：统一目标图层映射逻辑（传入原始几何对象）
    let targetLayer = getTargetLayerByGeometry(geometry);
    console.log('目标图层:', targetLayer);

    // WFS 更新事务
    const wfsTransaction = new WFS().writeTransaction(
      null,
      [updatedFeature],
      null,
      {
        featureNS: 'www.testmap.com',
        featurePrefix: 'testmap',
        featureType: targetLayer,
        srsName: 'EPSG:4326'
      }
    );
    
    sendWFSRequest(wfsTransaction, 'update');
    
  } catch (error) {
    console.error('更新过程中发生错误:', error);
    alert('更新失败: ' + error.message);
  }
}

// 删除要素
function deleteFeature(feature) {
  try {
    const featureId = feature.getId();
    if (!featureId) {
      throw new Error('要素没有ID，无法删除');
    }

    const geometry = feature.getGeometry();
    
    // 使用统一的目标图层映射函数
    let targetLayer = getTargetLayerByGeometry(geometry);

    // WFS 删除事务
    const wfsTransaction = new WFS().writeTransaction(
      null,
      null,
      [feature],
      {
        featureNS: 'www.testmap.com',
        featurePrefix: 'testmap',
        featureType: targetLayer,
        srsName: 'EPSG:4326'
      }
    );
    
    sendWFSRequest(wfsTransaction, 'delete');
    
  } catch (error) {
    console.error('删除过程中发生错误:', error);
    alert('删除失败: ' + error.message);
  }
}

// 带过滤条件的要素查询
function loadFeaturesWithFilter(filter = '') {
  try {
    // 清除现有要素
    vectorSource1.clear();
    vectorSource2.clear();
    vectorSource3.clear();
    
    let filterParam = '';
    if (filter) {
      filterParam = `&CQL_FILTER=${encodeURIComponent(filter)}`;
    }
    
    // 重新加载带过滤条件的要素
    vectorSource1.refresh();
    vectorSource2.refresh();
    vectorSource3.refresh();
    
    console.log(`执行要素查询，过滤条件: ${filter || '无'}`);
    
  } catch (error) {
    console.error('查询要素时发生错误:', error);
    alert('查询失败: ' + error.message);
  }
}

// 统一的WFS请求发送函数
function sendWFSRequest(wfsTransaction, operationType) {
  const serializer = new XMLSerializer();
  let xmlString = serializer.serializeToString(wfsTransaction);
  
  // 添加命名空间声明
  xmlString = xmlString.replace(
    '<Transaction',
    '<Transaction xmlns:wfs="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml" xmlns:testmap="www.testmap.com"'
  );
  
  // 根据操作类型处理GML格式
  if (operationType === 'insert') {
    const featureNode = wfsTransaction.getElementsByTagName('Feature')[0];
    if (featureNode) {
      const geometry = featureNode.getElementsByTagName('geom')[0];
      if (geometry) {
        const geomType = geometry.firstChild?.localName;
        if (geomType === 'Point') {
          xmlString = buildGmlPoint(xmlString, geometry);
        } else if (geomType === 'MultiLineString') {
          xmlString = buildGmlMultiLineString(xmlString, geometry);
        } else if (geomType === 'MultiPolygon') {
          xmlString = buildGmlMultiPolygon(xmlString, geometry);
        }
      }
    }
  }
  
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/api/geoserver/testmap/ows', true);
  xhr.setRequestHeader('Content-Type', 'text/xml');
  
  xhr.onload = function() {
    if (xhr.status === 200) {
      if (xhr.responseText && xhr.responseText.includes('Exception')) {
        console.error(`WFS-T ${operationType}事务返回错误:`, xhr.responseText);
        alert(`要素${getOperationName(operationType)}失败: GeoServer处理请求时发生错误`);
      } else {
        console.log(`WFS-T ${operationType}事务成功:`, xhr.responseText);
        alert(`要素${getOperationName(operationType)}成功！`);
        
        // 刷新图层数据
        setTimeout(() => {
          vectorSource1.refresh();
          vectorSource2.refresh();
          vectorSource3.refresh();
        }, 1000);
      }
    } else {
      console.error(`WFS-T ${operationType}事务失败:`, xhr.status, xhr.responseText);
      alert(`要素${getOperationName(operationType)}失败: ${xhr.status} ${xhr.statusText}`);
    }
  };
  
  xhr.onerror = function() {
    alert('网络错误，请检查GeoServer连接');
  };
  
  console.log(`发送的WFS-T ${operationType} XML请求:`, xmlString);
  xhr.send(xmlString);
}

function getOperationName(operationType) {
  const names = {
    'insert': '添加',
    'update': '更新',
    'delete': '删除'
  };
  return names[operationType] || '操作';
}

// GML构建函数（保持你原有的实现）
function buildGmlPoint(xmlString, geometry) {
  // 保持你原有的实现
  return xmlString;
}

function buildGmlMultiLineString(xmlString, geometry) {
  // 保持你原有的实现
  return xmlString;
}

function buildGmlMultiPolygon(xmlString, geometry) {
  // 保持你原有的实现
  return xmlString;
}

// 处理几何类型变化事件
function handleGeometryTypeChange() {
  if (draw) {
    map.removeInteraction(draw);
    draw = null;
  }
  
  if (selectedGeometryType.value !== 'None') {
    const interactions = map.getInteractions().getArray();
    interactions.forEach(interaction => {
      if (interaction instanceof Select || interaction instanceof Modify) {
        interaction.setActive(false);
      }
    });
    
    let drawStyle;
    if (selectedGeometryType.value === 'Point') {
      drawStyle = new Style({
        image: new Circle({
          radius: 4,
          fill: new Fill({
            color: 'rgba(255, 0, 0, 0.5)'
          }),
          stroke: new Stroke({
            color: '#ff0000',
            width: 2
          })
        })
      });
    } else {
      drawStyle = new Style({
        stroke: new Stroke({
          color: 'rgba(255, 0, 0, 0.5)',
          width: 2
        }),
        fill: new Fill({
          color: 'rgba(255, 0, 0, 0.2)'
        })
      });
    }
    
    draw = new Draw({
      source: vectorSource1,
      type: selectedGeometryType.value,
      style: drawStyle,
      geometryFunction: selectedGeometryType.value === 'Circle' ? 
        Draw.createRegularPolygon(36) : undefined
    });
    
    const mapElement = map.getTargetElement();
    switch(selectedGeometryType.value) {
      case 'Point':
      case 'LineString':
      case 'Polygon':
        mapElement.style.cursor = 'crosshair';
        break;
    }
    
    draw.on('drawstart', () => {
      console.log('开始绘制...');
      if (mapElement) {
        mapElement.style.cursor = 'crosshair';
      }
    });
    
    draw.on('drawend', (event) => {
      const feature = event.feature;
      const geometry = feature.getGeometry();
      console.log('绘制完成，几何类型:', geometry.getType());
      console.log('几何坐标:', JSON.stringify(geometry.getCoordinates()));
      
      feature.set('created', true);
      feature.set('creationTime', new Date().toISOString());
      
      let coordinateInfo = '';
      if (geometry.getType() === 'Point') {
        const coords = geometry.getCoordinates();
        coordinateInfo = `点坐标: [${coords[0].toFixed(6)}, ${coords[1].toFixed(6)}]`;
      } else if (geometry.getType() === 'LineString') {
        const coords = geometry.getCoordinates();
        coordinateInfo = `线段，包含 ${coords.length} 个点`;
      } else if (geometry.getType() === 'Polygon') {
        const coords = geometry.getCoordinates()[0];
        coordinateInfo = `多边形，包含 ${coords.length} 个顶点`;
      }
      
      console.log('坐标信息:', coordinateInfo);
      
      if (confirm(`绘制完成！${coordinateInfo}\n是否保存此要素到数据库？`)) {
        alert('正在保存要素到GeoServer，请稍候...');
        saveDrawnFeature(feature, selectedGeometryType.value);
      }
    });
    
    map.addInteraction(draw);
  } else {
    const interactions = map.getInteractions().getArray();
    interactions.forEach(interaction => {
      if (interaction instanceof Select || interaction instanceof Modify) {
        interaction.setActive(true);
      }
    });
    
    const mapElement = map.getTargetElement();
    mapElement.style.cursor = '';
  }
}

// 切换底图函数
function changeBasemap() {
  Object.keys(basemapLayers).forEach(key => {
    if (key !== 'none' && basemapLayers[key]) {
      basemapLayers[key].setVisible(key === selectedBasemap.value);
    }
  });
}

// 样式定义（保持你原有的样式）
const vectorLayer1Style = new Style({
  image: new Circle({
    radius: 6,
    fill: new Fill({
      color: 'rgba(0, 0, 255, 0.5)'
    }),
    stroke: new Stroke({
      color: 'blue',
      width: 2
    })
  }),
  stroke: new Stroke({
    color: 'blue',
    width: 1
  }),
  fill: new Fill({
    color: 'rgba(0, 0, 255, 0.1)'
  })
});

const vectorLayer2Style = new Style({
  stroke: new Stroke({
    color: 'red',
    width: 1
  }),
  fill: new Fill({
    color: 'rgba(255, 0, 0, 0.1)'
  })
});

const vectorLayer3Style = new Style({
  image: new Circle({
    radius: 4,
    fill: new Fill({
      color: 'skyblue'
    }),
    stroke: new Stroke({
      color: 'yellow',
      width: 1
    })
  })
});

const selectStyle = new Style({
  stroke: new Stroke({
    color: 'yellow',
    width: 2
  }),
  fill: new Fill({
    color: 'rgba(255, 255, 0, 0.3)'
  })
});

const modifyStyle = new Style({
  stroke: new Stroke({
    color: 'green',
    width: 2
  }),
  fill: new Fill({
    color: 'rgba(0, 255, 0, 0.3)'
  })
});

onMounted(() => {
  // 创建WFS矢量图层
  vectorSource1 = new VectorSource({
    format: new GeoJSON(),
    url: (extent, resolution, projection) => {
      const bbox = extent.join(',') + ',' + projection.getCode();
      return `/api/geoserver/testmap/ows?service=WFS&version=2.0.0&request=GetFeature&typeName=testmap%3Abou2_4l&outputFormat=application%2Fjson&bbox=${bbox}&count=5000`;
    },
    strategy: bbox
  });

  const vectorLayer1 = new VectorLayer({
    source: vectorSource1,
    style: vectorLayer1Style,
    renderMode: 'image'
  });

  vectorSource2 = new VectorSource({
    format: new GeoJSON(),
    url: (extent, resolution, projection) => {
      const bbox = extent.join(',') + ',' + projection.getCode();
      return `/api/geoserver/testmap/ows?service=WFS&version=2.0.0&request=GetFeature&typeName=testmap%3Abou2_4p&outputFormat=application%2Fjson&bbox=${bbox}&count=5000`;
    },
    strategy: bbox
  });

  const vectorLayer2 = new VectorLayer({
    source: vectorSource2,
    style: vectorLayer2Style,
    renderMode: 'image'
  });

  vectorSource3 = new VectorSource({
    format: new GeoJSON(),
    url: (extent, resolution, projection) => {
      const bbox = extent.join(',') + ',' + projection.getCode();
      return `/api/geoserver/testmap/ows?service=WFS&version=2.0.0&request=GetFeature&typeName=testmap:city&outputFormat=application/json&count=100`;
    },
    strategy: bbox
  });

  const vectorLayer3 = new VectorLayer({
    source: vectorSource3,
    style: vectorLayer3Style,
    renderMode: 'image'
  });

  // 统一的错误提示
  setTimeout(() => {
    if (vectorSource1.getState() !== 'ready' && vectorSource2.getState() !== 'ready' && vectorSource3.getState() !== 'ready') {
      alert('WFS图层加载失败，请检查服务地址和网络连接');
    }
  }, 5000);

  // ArcGIS世界街道图
  const arcgisLayer = new TileLayer({
    source: new XYZ({
      url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
      crossOrigin: 'anonymous',
      projection: 'EPSG:3857'
    }),
    name: 'arcgis',
    visible: false
  });

  // 保存底图图层引用
  basemapLayers = {
    'none': null,
    'arcgis': arcgisLayer
  };

  // 创建选择和修改交互
  select = new Select({
    layers: [vectorLayer3, vectorLayer1, vectorLayer2],
    style: selectStyle,
    condition: click
  });

  modify = new Modify({
    features: select.getFeatures(),
    style: modifyStyle,
    pixelTolerance: 5
  });

  // 监听要素选择事件
  select.on('select', (event) => {
    if (event.selected.length > 0) {
      selectedFeature.value = event.selected[0];
      console.log('选中要素:', selectedFeature.value.getId());
    } else {
      selectedFeature.value = null;
    }
  });

  // 初始化地图
  map = new Map({
    layers: [
      arcgisLayer,
      vectorLayer1,
      vectorLayer2,
      vectorLayer3
    ],
    interactions: defaultInteractions({
      altShiftDragRotate: false,
      pinchRotate: false
    }).extend([select, modify]),
    loadTilesWhileAnimating: true,
    loadTilesWhileInteracting: false,
    target: mapContainer.value,
    view: new View({
      center: fromLonLat([104.1954, 35.8617], 'EPSG:3857'),
      maxZoom: 19,
      zoom: 4,
      projection: 'EPSG:3857',
      enableRotation: false
    })
  });

  // 清理事件监听器
  onUnmounted(() => {
    if (map) {
      map.getInteractions().clear();
      map.getLayers().clear();
      map.setTarget(null);
      map = null;
    }
  });
});

// 声明需要暴露给模板的函数
defineExpose({
  handleGeometryTypeChange,
  changeBasemap,
  saveFeatures,
  updateSelectedFeature,
  deleteSelectedFeature,
  queryFeatures,
  closeFeatureInfo,
  startDrag,
  drag,
  stopDrag
});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

h1 {
  text-align: center;
  margin: 10px 0;
  color: #333;
}

.map {
  flex: 1;
  width: 100%;
  min-height: 500px;
  border: 1px solid #ccc;
}

.controls {
  text-align: center;
  margin-bottom: 10px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 5px;
}

.basemap-control, .draw-control {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  background: rgba(255, 255, 255, 0.9);
  padding: 8px 15px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin: 5px;
}

.draw-control {
  margin-top: 8px;
}

.basemap-control label, .draw-control label {
  font-weight: bold;
  color: #333;
  font-size: 14px;
}

.basemap-control select, .draw-control select {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  font-size: 14px;
  transition: border-color 0.3s;
}

.basemap-control select:hover, .draw-control select:hover {
  border-color: #4285f4;
}

.basemap-control button {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  margin-left: 5px;
}

.basemap-control button:hover {
  border-color: #4285f4;
  background: #f8f9fa;
}

.basemap-control button:disabled {
  background: #e9ecef;
  color: #6c757d;
  cursor: not-allowed;
  border-color: #dee2e6;
}

input {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 200px;
}

/* 要素信息悬浮弹窗样式 */
.feature-info-popup {
  position: fixed;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
  z-index: 1000;
  border: 1px solid #ddd;
  cursor: move; /* 鼠标指针样式 */
  user-select: none; /* 防止文本选择 */
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

.popup-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
}

.close-btn:hover {
  background: #e9ecef;
  color: #333;
}

.popup-content {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.info-section {
  margin-bottom: 20px;
}

.info-section h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
  border-bottom: 2px solid #4285f4;
  padding-bottom: 5px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 8px;
}

.info-item {
  display: grid;
  grid-template-columns: 120px 1fr;
  gap: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item label {
  font-weight: bold;
  color: #555;
}

.info-item span {
  color: #333;
  word-break: break-all;
}

.coordinates p {
  margin: 5px 0;
  color: #333;
  font-size: 14px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .feature-info-popup {
    width: 95%;
    max-height: 90vh;
  }
  
  .popup-content {
    padding: 15px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .info-item {
    grid-template-columns: 1fr;
    gap: 5px;
  }
  
  .info-item label {
    font-size: 14px;
    color: #666;
  }
}
</style>
